package com.itheima.controller;

import com.itheima.dto.MessageConstant;
import com.itheima.dto.PageResult;
import com.itheima.dto.QueryPageBean;
import com.itheima.dto.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private OrderService orderService;

    @Value("${health.path}")
    private String basePath;

    /**
     * 接口一 分页查询套餐
     *
     * @param qpb
     * @return
     */
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean qpb) {

        PageResult setmealPage = setmealService.findPage(qpb);

        return setmealPage;
    }

    /**
     * 接口二 新增套餐
     *
     * @param setmeal
     * @return
     */
    @PostMapping
    public Result addSetmeal(@RequestParam List<Integer> checkgroupIds, @RequestBody Setmeal setmeal) {

        setmealService.addSetmeal(checkgroupIds, setmeal);


        return Result.success("添加成功!");
    }

    /**
     * 接口三 图片上传
     *
     * @param imgFile
     * @return
     */

    //文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile)
    {
        System.out.println(imgFile);
        String originalFilename = imgFile.getOriginalFilename();
        assert originalFilename != null;
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index - 1);
        String fileName = UUID.randomUUID().toString() + extention;
        try
        {
            //将文件上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
        } catch (IOException e)
        {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL,"");
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
    }

//    @PostMapping("/upload")
//    public Result uploadImage(@RequestParam("imgFile") MultipartFile imgFile) {
//        //原始文件名
//        String originalFilename = imgFile.getOriginalFilename();
//
//        //根据 . 截取的字符串
//        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
//
//        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
//        String fileName = UUID.randomUUID().toString() + s;
//
//        //创建一个目录对象
//        File dir = new File(basePath);
////        //判断当前目录是否存在
////        if (!dir.exists()) {
////            //目录不存在，需要创建
////            dir.mkdirs();
////        }
//
//        try {
//            //将临时文件转存到指定位置
//            imgFile.transferTo(new File(basePath + fileName));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return Result.success(fileName);
//    }

    //下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应体的格式,固定格式
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接口四 删除套餐
     */
    @DeleteMapping("/{id}")
    public Result deleteSetmeal(@PathVariable Integer id) {
        //首先 根据套餐id查询order 看是否在被使用
        List<Order> orders = orderService.queryBySetmealId(id);

        if (null == orders || 0 == orders.size()) {//说明套餐没有被使用

            //调用套餐的删除方法
            setmealService.deleteSetmealById(id);

            return Result.success("删除成功!");

        }

        return Result.error("套餐正被订单使用,禁止删除");

    }

    /**
     * 接口五 根据id查询套餐
     *
     * @return
     */
    @GetMapping("/{id}")
    public Result queryById(@PathVariable Integer id) {

        Setmeal setmeal = setmealService.queryById(id);

        return Result.success(setmeal, MessageConstant.QUERY_SETMEAL_SUCCESS);
    }

    /**
     * 接口六 根据套餐id查询对应的检查组id集合
     *
     * @param setmealId
     * @return
     */
    @GetMapping("/checkgroup/{setmealId}")
    public Result queryCheckGroupIdsBySetmealId(@PathVariable Integer setmealId) {

        List<Integer> CheckGroupIds = setmealService.queryCheckGroupIdsBySetmealId(setmealId);

        return Result.success(CheckGroupIds, "查询成功!");
    }


    /**
     * 感觉和接口六有点像
     *
     * @param id
     * @return
     */
    @GetMapping("/findCheckGroupIdsBySetmealId")
    public Result findCheckGroupIdsBySetmealId(@RequestParam Integer id) {

        List<Integer> CheckGroupIds = setmealService.queryCheckGroupIdsBySetmealId(id);

        return Result.success(CheckGroupIds, "查询成功!");
    }

    /**
     * 接口七 编辑套餐
     *
     * @param checkgroupIds
     * @param setmeal
     */
    @PutMapping
    public Result updateSetmeal(@RequestParam List<Integer> checkgroupIds, @RequestBody Setmeal setmeal) {
        Integer setmealId = setmeal.getId();

        setmealService.updateSetmeal(setmeal,checkgroupIds);

        return Result.success("修改成功");
    }

}
